﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using TCM.DbContextt;
using TCM.Models;

namespace TCM.Forms
{
    public partial class RazdelsList : Form
    {
        private BaseContext db;

        public RazdelsList()
        {
            InitializeComponent();
            db = new BaseContext();
            LoadTable();
        }

        private void LoadTable()
        {
            db.Razdels.Load();

            dataGridView1.DataSource = db.Razdels.Local.ToBindingList();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            CategoriesManager Razdels = new CategoriesManager();

            var result = Razdels.ShowDialog(this);

            if (result == DialogResult.Cancel)
                return;

            Razdel Razdel = new Razdel();

            Razdel.RazdelId = Guid.NewGuid();
            Razdel.Name = Razdels.textBox1.Text;

            db.Razdels.Add(Razdel);

            db.SaveChanges();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int index = dataGridView1.SelectedRows[0].Index;
                Guid id = Guid.Empty;
                bool converted = Guid.TryParse(dataGridView1[0, index].Value.ToString(), out id);
                if (converted == false)
                    return;

                Razdel razdel = db.Razdels.Find(id);

                CategoriesManager RazdelManager = new CategoriesManager();


                RazdelManager.textBox1.Text = razdel.Name;

                DialogResult result = RazdelManager.ShowDialog(this);

                if (result == DialogResult.Cancel)
                    return;

                razdel.Name = RazdelManager.textBox1.Text;

                db.Entry(razdel).State = EntityState.Modified;
                db.SaveChanges();

                MessageBox.Show("Объект обновлен");

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int index = dataGridView1.SelectedRows[0].Index;
                Guid id = Guid.Empty;
                bool converted = Guid.TryParse(dataGridView1[0, index].Value.ToString(), out id);
                if (converted == false)
                    return;

                Razdel razdel = db.Razdels.Find(id);
                db.Razdels.Remove(razdel);
                db.SaveChanges();

                MessageBox.Show("Объект удален");
            }
        }
    }
}
